/**
 * axios网络请求 POST
 * @param api api名称
 * @param data 参数
 * @param func 成功回调
 * @param err 失败回调
 * @param header 头部
 */
function apiRequest(api, data, func, err,header ={}) {
    axios({
        method: 'POST',
        url: '/admin/' + api,
        data: data,
        headers: {
            token: localStorage.getItem('admin_token')
        }
    }).then(function (res) {
        if (res.status === 200) {
            var ret = res.data
            switch (ret.code) {
                case 200:
                    func(ret.data)
                    break
                case 100:
                    if (typeof err === 'function') {
                        err(ret)
                    } else {
                        coco.init()
                        coco.alert(ret.message)
                    }
                    break
                case 401:
                    var domain = 'http://'+window.location.host+'/admin/login/index';
                    location.href = domain;
                    break
            }
        } else {
            console.error('network error', res)
        }
    })
}

/**
 * Js网页跳转
 * @param url
 */
function urlTo(url) {
    var char = '?'
    if (url.indexOf('?') !== -1) {
        char = '&'
    }
    url += char
    window.location.href = url
}

function urlNew(url) {
    var char = '?'
    if (url.indexOf('?') !== -1) {
        char = '&'
    }
    url += char
    window.open(url,"_blank");
}

/**
 * 获取页面get参数(中文乱码)
 * @param name
 * @returns {string|null}
 */
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2])
    return null
}

// 封装去掉回车和空格方法
function myTrim(x) {
    var str = x.replace(/\s+/g, '')
    return str.replace(/[\r\n]/g, '')
}

// 时间戳转换
function timestampToTime(timestamp) {
    var date = new Date(timestamp);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-';
    var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var mm =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    return YY + MM + DD + ' ' + hh + mm;
}

// 图片格式
function isAssetTypeAnImage(ext) {
    return (
        [
            'png',
            'jpg',
            'jpeg',
            'bmp',
            'gif',
            'webp',
            'psd',
            'svg',
            'tiff'
        ].indexOf(ext.toLowerCase()) !== -1
    )
}

// 小时化为秒
function myH(x) {
    return Number(x * 3600)
}

// 分钟化为秒
function myM(x) {
    return Number(x * 60)
}

/**
 * 秒数时间格式化
 * @param seconds
 * @param isArr
 * @param isDay
 * @returns {arr|str}
 */
function secondsTimeFormat(seconds, isArr, isDay) {
    var returnArr = isArr || false;
    var returnDay = isDay || false;
    var d = Math.floor(seconds / 86400);
    var h = Math.floor((seconds - d * 86400) / 3600);
    var m = Math.floor((seconds - (d * 86400 + h * 3600)) / 60);
    var s = Math.floor(seconds - (d * 86400 + h * 3600 + m * 60));
    d = d.toString();
    h = h.toString();
    m = m.toString();
    s = s.toString();
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;
    if (returnDay) {
        return d + "天" + h + ":" + m + ":" + s
    } else if (returnArr) {
        return [d, h, m, s]
    } else {
        if (parseInt(h) === 0) {
            return m + ":" + s
        } else if (parseInt(d) === 0) {
            return h + ":" + m + ":" + s
        } else {
            return d + "天" + h + ":" + m + ":" + s
        }
    }
}

/**
 * laydate时间选择器配置
 * @param format
 * @param chooseCallback
 */
function layDateConfig(format, chooseCallback) {
    var formatStr = arguments[0] ? arguments[0] : 'YYYY-MM-DD hh:mm';
    var config = {
        format: formatStr,
        istime: formatStr !== 'YYYY-MM-DD',
        isclear: true,
        istoday: true,
        issure: true,
        festival: true,
        start: getNowTimeStr(),
        choose: function (date) {
            if (typeof chooseCallback === 'function') {
                chooseCallback(date)
            }
        }
    }
    laydate(config)
}

/**
 * 获取当前时间的字符串
 */
function getNowTimeStr() {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    }
    var date = now.getDate();
    if (date < 10) {
        date = '0' + date;
    }
    var hour = now.getHours();
    if (hour < 10) {
        hour = '0' + hour;
    }
    var minute = now.getMinutes();
    if (minute < 10) {
        minute = '0' + minute;
    }
    return year + '-' + month + '-' + date + ' ' + hour + ':' + minute;
}

/**
 * 文件域自动上传
 * @param e
 * @param callback
 * @param onPercentage
 */
function autoFileUpload(e, callback, onPercentage) {
    var file = e.files[0];
    var formData = new FormData();
    formData.append('file', file);
    $.ajax({
        url: '/common/file/upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function () {
            console.log('正在上传')
        },
        dataType: 'json',
        xhr: function () {
            var xhr = new XMLHttpRequest();
            xhr.upload.onprogress = function (e) {
                var progressRate = (e.loaded / e.total) * 100;
                console.log('percentage', progressRate);
                if (typeof onPercentage === 'function') {
                    onPercentage(progressRate);
                }
            }
            return xhr;
        },
        success: function (res) {
            console.log(res)
            if (res.code === 200) {
                var url = res.data;
                callback(url);
            } else {
                console.error(res);
                alert(res.msg);
            }
        }
    });
}

/**
 * 初始化vue h5 editor
 */
function initVueEditor() {
    Vue.use(VueHtml5Editor, {
        showModuleName: true,
        image: {
            // 文件最大体积，单位字节  max file size
            sizeLimit: 5 * 1024 * 1024,
            // 上传参数,默认把图片转为base64而不上传
            // upload config,default null and convert image to base64
            upload: {
                url: '/common/file/upload',
                headers: {},
                params: {
                    type: 'form'
                },
                fieldName: 'file'
            },
            // 压缩参数,默认使用localResizeIMG进行压缩,设置为null禁止压缩
            // compression config,default resize image by localResizeIMG (https://github.com/think2011/localResizeIMG)
            // set null to disable compression
            // compress: {
            //     width: 1600,
            //     height: 1600,
            //     quality: 80
            // },
            // 响应数据处理,最终返回图片链接
            uploadHandler: function (res) {
                var json = JSON.parse(res);
                if (json.code === 200) {
                    return json.data;
                } else {
                    console.error('editor file upload error', json);
                }
            }
        },
        language: "zh-cn",
        // 隐藏不想要显示出来的模块
        hiddenModules: ["info"],
        modules: [
            {
                name: 'video',
                icon: 'fa fa-video-camera',
                i18n: 'video',
                show: true,
                init: function(editor) {
                    console.log('emoji module init')
                },
                //vue component
                dashboard: {
                    template: '<div id="video" style="display:flex;align-items: center;">' +
                        '<input type="text" v-model="videoUrl" placeholder="视频链接">' +
                        '<input type="text" v-model="videoImg" placeholder="图片链接">' +
                        '<button style="margin: 2px 0 0 15px;" @click="submit">确定</button>' +
                        '</div>',
                    data: function() {
                        return {
                            videoUrl: '',
                            videoImg: ''
                        }
                    },
                    methods: {
                        submit: function() {
                            this.$parent.focus();
                            this.$parent.toggleDashboard();
                            this.$parent.execCommand('insertHTML', '<video src="' + this.videoUrl + '" poster="' + this.videoImg + '" autoplay controls x5-video-player-type="h5" class="w100" style="width:100%;" x5-video-orientation="portraint">')
                            this.videoUrl = ''
                        }
                    }
                }
            }
        ]
        // 自定义要显示的模块，并控制顺序
//         visibleModules: [
// //    "text",
// //    "color",
//             "font",
//             "align",
// //    "list",
// //    "link",
// //    "unlink",
// //    "tabulation",
//             "image",
// //    "hr",
// //    "eraser",
//             "undo",
// //    "full-screen",
// //    "info",
//         ],
    });
}

/**
 * 给富文本中插入的图片添加样式 width="100%"
 */
function setW100ForContentImg(data) {
    return data.replace(/<img/g, '<img width="100%"');
}